<template>
  <div class="p-6 bg-gray-50 min-h-full">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800 mb-2">知识库管理</h1>
      <p class="text-gray-600">支持多模态知识入库，包括文档、图片等多种格式</p>
    </div>

    <!-- 操作区域 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-gray-800">知识入库</h3>
        <div class="space-x-2">
          <a-button @click="showBatchUpload = true">
            <span class="icon-[mdi--upload-multiple] mr-1"></span>
            批量上传
          </a-button>
          <a-button type="primary" @click="showUploadModal = true">
            <span class="icon-[mdi--plus] mr-1"></span>
            知识入库
          </a-button>
        </div>
      </div>

      <!-- 快速统计 -->
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="text-center p-4 bg-blue-50 rounded-lg">
          <div class="text-2xl font-bold text-blue-600">{{ stats.totalFiles }}</div>
          <div class="text-sm text-gray-600">总文件数</div>
        </div>
        <div class="text-center p-4 bg-green-50 rounded-lg">
          <div class="text-2xl font-bold text-green-600">{{ stats.documents }}</div>
          <div class="text-sm text-gray-600">文档数量</div>
        </div>
        <div class="text-center p-4 bg-purple-50 rounded-lg">
          <div class="text-2xl font-bold text-purple-600">{{ stats.images }}</div>
          <div class="text-sm text-gray-600">图片数量</div>
        </div>
        <div class="text-center p-4 bg-orange-50 rounded-lg">
          <div class="text-2xl font-bold text-orange-600">{{ stats.totalSize }}</div>
          <div class="text-sm text-gray-600">总存储</div>
        </div>
      </div>
    </div>

    <!-- 知识库列表 -->
    <div class="bg-white rounded-lg shadow-sm p-6">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-gray-800">知识库内容</h3>
        <div class="flex items-center space-x-2">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索知识内容..."
            style="width: 200px"
            @search="handleSearch"
          />
          <a-select v-model:value="filterType" style="width: 120px" @change="handleFilter">
            <a-select-option value="">全部类型</a-select-option>
            <a-select-option value="document">文档</a-select-option>
            <a-select-option value="image">图片</a-select-option>
          </a-select>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="filteredData"
        :pagination="{ pageSize: 10, showSizeChanger: true }"
        :loading="loading"
        :scroll="{ y: 'calc(100vh - 600px)' }"
        class="scrollBarY"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'preview'">
            <div class="flex items-center space-x-2">
              <img
                v-if="record.type === 'image'"
                :src="record.url"
                class="w-10 h-10 object-cover rounded"
                @click="previewFile(record)"
              />
              <div
                v-else
                class="w-10 h-10 flex items-center justify-center bg-gray-100 rounded"
                @click="previewFile(record)"
              >
                <span :class="getFileIcon(record.fileType)" class="text-lg"></span>
              </div>
              <div>
                <div class="font-medium text-sm">{{ record.title }}</div>
                <div class="text-xs text-gray-500">{{ record.fileName }}</div>
              </div>
            </div>
          </template>

          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeLabel(record.type) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'status'">
            <a-tag
              :color="
                record.status === 'processed'
                  ? 'green'
                  : record.status === 'processing'
                    ? 'orange'
                    : 'red'
              "
            >
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>

          <!-- 添加标签列的渲染 -->
          <template v-if="column.key === 'tags'">
            <div class="space-x-1">
              <a-tag v-for="tag in record.tags" :key="tag" color="blue" class="mb-1">
                {{ tag }}
              </a-tag>
              <span v-if="!record.tags || record.tags.length === 0" class="text-gray-400 text-sm">
                暂无标签
              </span>
            </div>
          </template>

          <template v-if="column.key === 'actions'">
            <div class="space-x-1">
              <a-button type="primary" size="small" @click="previewFile(record)">预览</a-button>
              <a-button type="primary" size="small" danger @click="deleteKnowledge(record)">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 上传弹窗 -->
    <a-modal
      v-model:open="showUploadModal"
      title="新增知识"
      width="600px"
      @ok="handleUpload"
      :confirm-loading="uploading"
    >
      <a-form :model="uploadForm" layout="vertical">
        <a-form-item label="知识标题" required>
          <a-input v-model:value="uploadForm.title" placeholder="请输入知识标题" />
        </a-form-item>

        <a-form-item label="知识描述">
          <a-textarea
            v-model:value="uploadForm.description"
            placeholder="请输入知识描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="文件上传" required>
          <a-upload-dragger
            v-model:fileList="uploadForm.fileList"
            :before-upload="beforeUpload"
            :multiple="true"
            accept=".pdf,.doc,.docx,.ppt,.pptx,.jpg,.jpeg,.png,.gif"
          >
            <p class="ant-upload-drag-icon">
              <span class="icon-[mdi--cloud-upload] text-4xl text-blue-500"></span>
            </p>
            <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p class="ant-upload-hint">支持文档(PDF、Word、PPT)、图片(JPG、PNG、GIF)等格式</p>
          </a-upload-dragger>
        </a-form-item>

        <a-form-item label="标签">
          <a-select
            v-model:value="uploadForm.tags"
            mode="tags"
            placeholder="添加标签"
            style="width: 100%"
          >
            <a-select-option v-for="tag in commonTags" :key="tag" :value="tag">
              {{ tag }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 批量上传弹窗 -->
    <a-modal
      v-model:open="showBatchUpload"
      title="批量上传"
      width="800px"
      @ok="handleBatchUpload"
      :confirm-loading="batchUploading"
    >
      <a-upload-dragger
        v-model:fileList="batchFileList"
        :before-upload="() => false"
        :multiple="true"
        accept=".pdf,.doc,.docx,.ppt,.pptx,.jpg,.jpeg,.png,.gif"
      >
        <p class="ant-upload-drag-icon">
          <span class="icon-[mdi--upload-multiple] text-4xl text-blue-500"></span>
        </p>
        <p class="ant-upload-text">批量上传文件</p>
        <p class="ant-upload-hint">支持多文件同时上传，系统将自动识别文件类型并处理</p>
      </a-upload-dragger>

      <div v-if="batchFileList.length" class="mt-4">
        <h4>待上传文件列表 ({{ batchFileList.length }} 个文件)</h4>
        <div class="max-h-60 overflow-y-auto">
          <div
            v-for="file in batchFileList"
            :key="file.uid"
            class="flex items-center justify-between p-2 border-b"
          >
            <div class="flex items-center space-x-2">
              <span :class="getFileIcon(getFileType(file.name))" class="text-lg"></span>
              <span>{{ file.name }}</span>
            </div>
            <span class="text-sm text-gray-500">{{ formatFileSize(file.size) }}</span>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 预览弹窗 -->
    <a-modal v-model:open="showPreview" :title="previewData?.title" width="800px" :footer="null">
      <div v-if="previewData">
        <div v-if="previewData.type === 'image'" class="text-center">
          <img :src="previewData.url" class="max-w-full max-h-96 object-contain" />
        </div>
        <div v-else-if="previewData.type === 'document'" class="space-y-4">
          <div class="flex items-center space-x-4">
            <span :class="getFileIcon(previewData.fileType)" class="text-2xl"></span>
            <div>
              <div class="font-medium">{{ previewData.fileName }}</div>
              <div class="text-sm text-gray-500">{{ previewData.fileSize }}</div>
            </div>
          </div>
          <div class="p-4 bg-gray-50 rounded">
            <p>{{ previewData.description || '暂无描述' }}</p>
          </div>
          <a-button type="primary" @click="downloadFile(previewData)">
            <span class="icon-[mdi--download] mr-1"></span>
            下载文件
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'

// 响应式数据
const loading = ref(false)
const uploading = ref(false)
const batchUploading = ref(false)
const showUploadModal = ref(false)
const showBatchUpload = ref(false)
const showPreview = ref(false)
const searchText = ref('')
const filterType = ref('')

// 统计数据
const stats = ref({
  totalFiles: 1247,
  documents: 856,
  images: 324,
  totalSize: '2.3GB',
})

// 上传表单
const uploadForm = ref({
  title: '',
  description: '',
  fileList: [],
  tags: [],
})

const batchFileList = ref([])
const previewData = ref(null)

// 常用标签
const commonTags = ['技术文档', '产品资料', '培训材料', '规范标准', '操作手册']

// 表格列配置
const columns = [
  { title: '预览', key: 'preview', width: 200 },
  { title: '类型', key: 'type', width: 100 },
  { title: '文件大小', dataIndex: 'fileSize', key: 'fileSize', width: 100 },
  { title: '状态', key: 'status', width: 100 },
  { title: '标签', dataIndex: 'tags', key: 'tags', width: 150 },
  { title: '上传时间', dataIndex: 'uploadTime', key: 'uploadTime', width: 150 },
  { title: '操作', key: 'actions', width: 180 },
]

// 模拟数据
const knowledgeData = ref([
  {
    id: 1,
    title: '产品技术规范文档',
    fileName: '产品规范.pdf',
    fileType: 'pdf',
    type: 'document',
    url: '/files/product-spec.pdf',
    fileSize: '2.3MB',
    status: 'processed',
    tags: ['技术文档', '产品资料'],
    description: '详细的产品技术规范说明文档',
    uploadTime: '2025-01-15 14:30',
  },
  {
    id: 2,
    title: '系统架构图',
    fileName: 'architecture.png',
    fileType: 'png',
    type: 'image',
    url: 'https://via.placeholder.com/400x300/4f46e5/ffffff?text=Architecture',
    fileSize: '856KB',
    status: 'processed',
    tags: ['架构图', '技术文档'],
    description: '系统整体架构设计图',
    uploadTime: '2025-01-15 13:45',
  },
  {
    id: 3,
    title: '用户操作手册',
    fileName: '操作手册.docx',
    fileType: 'docx',
    type: 'document',
    url: '/files/user-manual.docx',
    fileSize: '1.2MB',
    status: 'processing',
    tags: ['操作手册', '用户指南'],
    description: '详细的用户操作指南',
    uploadTime: '2025-01-15 12:20',
  },
  {
    id: 4,
    title: '培训PPT',
    fileName: '新员工培训.pptx',
    fileType: 'pptx',
    type: 'document',
    url: '/files/training.pptx',
    fileSize: '5.6MB',
    status: 'processed',
    tags: ['培训材料', '人力资源'],
    description: '新员工入职培训演示文稿',
    uploadTime: '2025-01-15 11:15',
  },
  {
    id: 5,
    title: '流程图示例',
    fileName: 'workflow.jpg',
    fileType: 'jpg',
    type: 'image',
    url: 'https://via.placeholder.com/600x400/10b981/ffffff?text=Workflow',
    fileSize: '432KB',
    status: 'processed',
    tags: ['流程图', '业务流程'],
    description: '业务流程示意图',
    uploadTime: '2025-01-15 10:30',
  },
])

// 计算属性
const filteredData = computed(() => {
  let data = knowledgeData.value

  if (searchText.value) {
    data = data.filter(
      (item) =>
        item.title.includes(searchText.value) ||
        item.fileName.includes(searchText.value) ||
        item.tags.some((tag) => tag.includes(searchText.value)),
    )
  }

  if (filterType.value) {
    data = data.filter((item) => item.type === filterType.value)
  }

  return data
})

// 方法
const getFileIcon = (fileType) => {
  const icons = {
    pdf: 'icon-[mdi--file-pdf-box] text-red-500',
    doc: 'icon-[mdi--file-word-box] text-blue-500',
    docx: 'icon-[mdi--file-word-box] text-blue-500',
    ppt: 'icon-[mdi--file-powerpoint-box] text-orange-500',
    pptx: 'icon-[mdi--file-powerpoint-box] text-orange-500',
    jpg: 'icon-[mdi--file-image] text-green-500',
    jpeg: 'icon-[mdi--file-image] text-green-500',
    png: 'icon-[mdi--file-image] text-green-500',
    gif: 'icon-[mdi--file-image] text-green-500',
  }
  return icons[fileType] || 'icon-[mdi--file] text-gray-500'
}

const getTypeColor = (type) => {
  const colors = {
    document: 'blue',
    image: 'green',
    video: 'purple',
  }
  return colors[type] || 'default'
}

const getTypeLabel = (type) => {
  const labels = {
    document: '文档',
    image: '图片',
  }
  return labels[type] || type
}

const getStatusLabel = (status) => {
  const labels = {
    processed: '已处理',
    processing: '处理中',
    failed: '处理失败',
  }
  return labels[status] || status
}

const getFileType = (fileName) => {
  return fileName.split('.').pop().toLowerCase()
}

const formatFileSize = (size) => {
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB'
  return (size / (1024 * 1024)).toFixed(1) + 'MB'
}

const beforeUpload = (file) => {
  const isValidType = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/gif',
    'video/mp4',
    'video/avi',
  ].includes(file.type)

  if (!isValidType) {
    message.error('不支持的文件格式！')
    return false
  }

  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    message.error('文件大小不能超过 50MB！')
    return false
  }

  return false // 阻止自动上传
}

const handleUpload = async () => {
  if (!uploadForm.value.title || !uploadForm.value.fileList.length) {
    message.error('请填写标题并上传文件！')
    return
  }

  uploading.value = true
  try {
    // 这里应该调用实际的上传API
    const formData = new FormData()
    formData.append('title', uploadForm.value.title)
    formData.append('description', uploadForm.value.description)
    formData.append('tags', JSON.stringify(uploadForm.value.tags))

    // 添加文件到FormData
    uploadForm.value.fileList.forEach((file, index) => {
      formData.append(`files[${index}]`, file.originFileObj || file)
    })

    // 调用上传API - 这里需要替换为你的实际API
    // const response = await addKnowledge(formData)

    // 模拟上传成功，添加到列表
    uploadForm.value.fileList.forEach((file) => {
      const newItem = {
        id: Date.now() + Math.random(),
        title: uploadForm.value.title,
        fileName: file.name,
        fileType: getFileType(file.name),
        type: file.type?.startsWith('image/')
          ? 'image'
          : file.type?.startsWith('video/')
            ? 'video'
            : 'document',
        url: URL.createObjectURL(file.originFileObj || file),
        fileSize: formatFileSize(file.size),
        status: 'processed', // 改为已处理状态
        tags: uploadForm.value.tags,
        description: uploadForm.value.description,
        uploadTime: new Date().toLocaleString(),
      }
      knowledgeData.value.unshift(newItem)
    })

    message.success('知识上传成功！')
    showUploadModal.value = false
    uploadForm.value = { title: '', description: '', fileList: [], tags: [] }

    // 更新统计数据
    updateStats()
  } catch (error) {
    console.error('上传失败:', error)
    message.error('上传失败！请重试')
  } finally {
    uploading.value = false
  }
}

const handleBatchUpload = async () => {
  if (!batchFileList.value.length) {
    message.error('请选择要上传的文件！')
    return
  }

  batchUploading.value = true
  try {
    // 这里应该调用批量上传API
    const formData = new FormData()
    batchFileList.value.forEach((file, index) => {
      formData.append(`files[${index}]`, file)
    })

    // 调用批量上传API
    // const response = await addKnowledge(formData)

    // 模拟批量上传成功
    batchFileList.value.forEach((file) => {
      const newItem = {
        id: Date.now() + Math.random(),
        title: file.name.split('.')[0],
        fileName: file.name,
        fileType: getFileType(file.name),
        type: file.type?.startsWith('image/')
          ? 'image'
          : file.type?.startsWith('video/')
            ? 'video'
            : 'document',
        url: URL.createObjectURL(file),
        fileSize: formatFileSize(file.size),
        status: 'processed', // 改为已处理状态
        tags: [],
        description: '',
        uploadTime: new Date().toLocaleString(),
      }
      knowledgeData.value.unshift(newItem)
    })

    message.success(`成功上传 ${batchFileList.value.length} 个文件！`)
    showBatchUpload.value = false
    batchFileList.value = []

    // 更新统计数据
    updateStats()
  } catch (error) {
    console.error('批量上传失败:', error)
    message.error('批量上传失败！请重试')
  } finally {
    batchUploading.value = false
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

const handleFilter = () => {
  // 过滤逻辑已在计算属性中实现
}

const previewFile = (record) => {
  previewData.value = record
  showPreview.value = true
}

const editKnowledge = (record) => {
  message.info('编辑功能开发中...')
}

const deleteKnowledge = (record) => {
  const index = knowledgeData.value.findIndex((item) => item.id === record.id)
  if (index > -1) {
    knowledgeData.value.splice(index, 1)
    message.success('删除成功！')
    // 删除后更新统计
    updateStats()
  }
}

const downloadFile = (record) => {
  // 模拟下载
  const link = document.createElement('a')
  link.href = record.url
  link.download = record.fileName
  link.click()
  message.success('开始下载...')
}

onMounted(() => {
  // 初始化统计数据
  updateStats()
})

// 更新统计数据
const updateStats = () => {
  const totalFiles = knowledgeData.value.length
  const documents = knowledgeData.value.filter((item) => item.type === 'document').length
  const images = knowledgeData.value.filter((item) => item.type === 'image').length
  const videos = knowledgeData.value.filter((item) => item.type === 'video').length

  stats.value = {
    totalFiles,
    documents,
    images,
    totalSize: '2.3GB', // 这里可以计算实际大小
  }
}
</script>
